package main

import (
	"fmt"
	v1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/klog/v2"
	"sigs.k8s.io/controller-runtime/pkg/client/config"
	"time"
)

func main() {
	getConfig, err := config.GetConfig()
	if err != nil {
		panic(err)
		return
	}
	clientSet, err := kubernetes.NewForConfig(getConfig)
	if err != nil {
		panic(err)
		return
	}

	informerFactory := informers.NewSharedInformerFactory(clientSet, 30*time.Second)
	deploymentInformer := informerFactory.Apps().V1().Deployments()
	informer := deploymentInformer.Informer()
	deploymentLister := deploymentInformer.Lister()
	_, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    addFunc,
		UpdateFunc: updateFunc,
		DeleteFunc: deleteFunc,
	})
	if err != nil {
		panic(err)
		return
	}

	stopper := make(chan struct{})
	defer close(stopper)
	informerFactory.Start(stopper)
	informerFactory.WaitForCacheSync(stopper)
	deployments, err := deploymentLister.Deployments("default").List(labels.Everything())
	if err != nil {
		panic(err)
	}
	for index, deploy := range deployments {
		fmt.Printf("%d-->%s\n", index, deploy.Name)
	}
	select {}
}

func addFunc(obj interface{}) {
	deploy := obj.(*v1.Deployment)
	klog.Infoln("add deploy", deploy.Name)
}

func updateFunc(old, new interface{}) {
	oldDeploy := old.(*v1.Deployment)
	newDeploy := new.(*v1.Deployment)
	klog.Infoln("update deploy", oldDeploy.Status.Replicas, newDeploy.Status.Replicas)
}

func deleteFunc(obj interface{}) {
	deploy := obj.(*v1.Deployment)
	klog.Infoln("delete deploy", deploy.Name)
}
